<?php

class Database 
{
	private $host;
	private $dbname;
	private $user;
	private $pass;
	
	private $data_set = false;
	private $connected = false;
	private $default_filename = "../mysqlconfig.txt";

	public $table_prefix;


	function Database($filename = "") {
		if(empty($filename)) {
			$filename = $this->default_filename;
		}
		return $this->readConfigFile($filename);
	}


	function readConfigFile($filename) {
		$lines = file($filename);
		$count = 0;
		
		foreach($lines as $pair) {
			$subs = explode("\t", trim($pair));


			switch($subs[0]) {
				case "host":
					$this->host = $subs[1];
					$count++;
					break;
					
				case "db":
					$this->dbname = $subs[1];
					$count++;
					break;
					
				case "user":
					$this->user = $subs[1];
					$count++;
					break;
					
				case "pass":
					$this->pass = $subs[1];
					$count++;
					break;
					
				default:
					echo "WARNING: Unknown key found in database config file.<br>\n";

			}
			
		}
		
		if($count < 4) {
			echo "ERROR: Not all neccesairy pairs were found in database config file.<br>\n";
			return false;
		}
		elseif($count > 4) {
			echo "WARNING: Double keys found in database config file, last keys are used.<br>\n";
			$this->data_set = true;
			return true;
		}
		else {
			$this->data_set = true;
			return true;
		}
	}
	
	
	function connectWithDb() {
		if(!$this->data_set) {
			$this->readConfigFile($this->default_filename);
			if(!$this->data_set) {
				echo "ERROR: No data set. Please call readConfigFile with the correct path.<br>\n";
				return false;
			}
			
			echo "WARNING: Please call readConfigFile yourself the next time.<br>\n";
		}
		
		if($this->connected) {
			echo "WARNING: You have already connected, doing it again.<br>\n";
		}
		
		$link = mysql_connect($this->host, $this->user, $this->pass);
		mysql_select_db($this->dbname, $link);
		
		$this->connected = true;
		return $link;
	}
	
	
	function executeQuery($link, $query) {
		if(!$this->connected) {
			if(!$this->connectWithDb()) {
				return false;
			}
		}
		
		$res = mysql_query($query);
		
		if(!$res) {
			echo "ERROR: Query failed, error: " . mysql_error() . ".<br>\n";
			return false;
		}
		
		if(@mysql_num_rows($res) > 1) {
			$ret = array();

			while($fetch = mysql_fetch_assoc($res)) {
				$ret[] = $fetch;
			}
			
			return $ret;
		}
		elseif(@mysql_num_rows($res) == 1) {
			return mysql_fetch_assoc($res);
		}
		else {
			return true;
		}
	
	}


}


?>

